using AutoMapper;
using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using S.M.SmartMedical.API.Write.Application.Command;
using S.M.SmartMedical.Domain.DTOs;
using S.M.SmartMedical.Domain.Entities;
using S.M.SmartMedical.ErrorCode;
using S.M.SmartMedical.Infrastructure.BaseRepository;
using System;

namespace S.M.SmartMedical.API.Write.Application.Handler
{
    /// <summary>
    /// 更新医院命令处理程序
    /// 处理医院更新逻辑
    /// </summary>
    public class UpdateHospitalHandler : IRequestHandler<UpdateHospitalCommand, APIResult<HospitalDto>>
    {
        private readonly IRepository<Hospital> _hospitalRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<UpdateHospitalHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public UpdateHospitalHandler(
            IRepository<Hospital> hospitalRepository,
            IMapper mapper,
            ILogger<UpdateHospitalHandler> logger)
        {
            _hospitalRepository = hospitalRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理更新医院请求
        /// </summary>
        public async Task<APIResult<HospitalDto>> Handle(UpdateHospitalCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始更新医院，ID：{Id}", request.Id);

                // 查找医院
                var hospital = await _hospitalRepository.GetAsync(h => h.Id == request.Id && !h.IsDeleted);

                if (hospital == null)
                {
                    _logger.LogWarning("未找到ID为 {Id} 的医院", request.Id);
                    return new APIResult<HospitalDto>
                    {
                        Code = APIEnum.Fail,
                        Message = "未找到该医院"
                    };
                }

                // 更新医院信息
                hospital.Name = request.Name;
                hospital.ImageUrl = request.ImageUrl;
                hospital.Level = request.Level;
                hospital.Type = request.Type;
                hospital.Address = request.Address;
                hospital.Phone = request.Phone;
                hospital.Description = request.Description;
                hospital.IsEnabled = request.IsEnabled;
                hospital.UpdateTime = DateTime.Now;

                // 保存到数据库
                var result = await _hospitalRepository.UpdateAsync(hospital);
                if (result <= 0)
                {
                    _logger.LogError("更新医院失败，数据库保存失败");
                    return new APIResult<HospitalDto>
                    {
                        Code = APIEnum.Fail,
                        Message = "更新医院失败"
                    };
                }

                // 映射到DTO并返回
                var hospitalDto = _mapper.Map<HospitalDto>(hospital);

                _logger.LogInformation("医院更新成功，ID：{Id}", request.Id);

                return new APIResult<HospitalDto>
                {
                    Code = APIEnum.OK,
                    Message = "医院更新成功",
                    Data = hospitalDto
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新医院时发生错误，ID：{Id}", request.Id);
                return new APIResult<HospitalDto>
                {
                    Code = APIEnum.Fail,
                    Message = "更新失败：" + ex.Message
                };
            }
        }
    }
}